<!DOCTYPE html>
<html>
<head>
    <title>页面编辑</title>
    {% include 'system/common/header.html' %}</head>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/aieditor/style.css') }}"/>
    <style>

    </style>
<body>
<form class="layui-form" action="">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-form-item layui-hide">
                    <label class="layui-form-label">编号</label>
                    <div class="layui-input-block">
                        <input type="text" value="{{ post.id }}" name="postId" lay-verify="required"
                               autocomplete="off" placeholder="页面编号" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">页面标题</label>
                    <div class="layui-input-block">
                        <input type="text" value="{{ post.title or '' }}" name="title" lay-verify="required"
                               autocomplete="off" placeholder="页面标题" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">页面别名</label>
                    <div class="layui-input-block">
                        <input type="text" value="{{ post.slug or '' }}" name="slug" lay-verify="required"
                               autocomplete="off" placeholder="页面别名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">页面摘要</label>
                    <div class="layui-input-block">
                        <textarea placeholder="页面摘要" name="excerpt" class="layui-textarea">{{ post.excerpt or '' }}</textarea>
                    </div>
                </div>
                
                <!-- 特色图像 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">特色图像</label>
                    <div class="layui-input-block">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <input type="text" name="featured_image" id="featured-image-url" placeholder="请输入图片地址或上传图片" value="{{ post.featured_image or '' }}" class="layui-input">
                            </div>
                            <div class="layui-col-md6">
                                <button type="button" class="layui-btn layui-btn-primary" id="upload-featured-image">
                                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="paste-image-url">
                                    <i class="layui-icon layui-icon-link"></i> 粘贴地址
                                </button>
                            </div>
                        </div>
                        <div id="featured-image-preview" style="margin-top: 10px; display: none;">
                            <img id="preview-img" src="" alt="特色图像预览" style="max-width: 300px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 2px;">
                            <div style="margin-top: 5px;">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="remove-featured-image">
                                    <i class="layui-icon layui-icon-close"></i> 移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">页面内容</label>
                    <div class="layui-input-block">
                        <div id="editor" style="height: 550px"></div>
                    </div>
                </div>
                
                <!-- SEO信息 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_title" placeholder="SEO标题（可选）" value="{{ post.meta_title or '' }}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_keywords" placeholder="SEO关键词，多个关键词用逗号分隔（可选）" value="{{ post.meta_keywords or '' }}" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">SEO描述</label>
                    <div class="layui-input-block">
                        <textarea name="meta_description" placeholder="SEO描述（可选）" class="layui-textarea" style="height: 80px;">{{ post.meta_description or '' }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit=""
                    lay-filter="page-update">
                <i class="layui-icon layui-icon-ok"></i>
                草稿
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="publish-btn">
                <i class="layui-icon layui-icon-release"></i>
                发布
            </button>
        </div>
    </div>
</form>
{% include 'system/common/footer.html' %}
<script src="{{ url_for('admin.static', filename='system/component/aieditor/index.js') }}"></script>
<script>
// 调试脚本
console.log('=== 页面编辑页面调试 ===');

// 获取页面内容并设置为全局变量
window.postContent = '';
console.log('页面内容:', window.postContent);
console.log('页面内容类型:', typeof window.postContent);
console.log('页面内容长度:', window.postContent ? window.postContent.length : 0);
console.log('页面ID:', "{{ post.id }}");
console.log('页面标题:', "{{ post.title or '' }}");
console.log('页面别名:', "{{ post.slug or '' }}");
console.log('页面摘要:', "{{ post.excerpt|safe if post.excerpt else '' }}");
</script>
<script type="module">
    import {AiEditor} from "{{ url_for('admin.static', filename='system/component/aieditor/index.js') }}";
    
    // 等待DOM加载完成后初始化AiEditor
    document.addEventListener('DOMContentLoaded', function() {
        // 获取页面内容
        const postId = "{{ post.id }}";
        console.log('获取页面ID:', postId);
        
        // 通过AJAX获取页面内容
        console.log('开始获取页面内容，ID:', postId);
        fetch(`/admin/cms/page/content/${postId}`)
            .then(response => {
                console.log('AJAX响应状态:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('AJAX响应数据:', data);
                if (data.success) {
                    window.postContent = data.data.content || '';
                    console.log('获取到页面内容:', window.postContent);
                } else {
                    console.warn('获取页面内容失败:', data.msg);
                    window.postContent = '';
                }
                
                // 初始化AiEditor
                initAiEditor();
            })
            .catch(error => {
                console.error('获取页面内容出错:', error);
                window.postContent = '';
                initAiEditor();
            });
        
                    // 初始化AiEditor函数
            const initAiEditor = () => {
                console.log('初始化AiEditor，内容:', window.postContent);
                
                window.aiEditor = new AiEditor({
                    element: "#editor",
                    placeholder: "点击输入内容...",
                    content: window.postContent,
                    image: {
                        allowBase64: false,
                        defaultSize: 350,
                        uploadUrl: "/admin/cms/page/upload",
                        uploadFormName: "image",
                        uploaderEvent: {
                            onUploadBefore: (file, uploadUrl, headers) => {
                                console.log('图片上传开始:', file.name);
                            },
                            onSuccess: (file, response) => {
                                console.log('图片上传成功:', response);
                            },
                            onFailed: (file, response) => {
                                console.error('图片上传失败:', response);
                            },
                            onError: (file, error) => {
                                console.error('图片上传错误:', error);
                            },
                        },
                        bubbleMenuItems: ["AlignLeft", "AlignCenter", "AlignRight", "delete"]
                    },
                    video: {
                        uploadUrl: "/admin/cms/page/upload",
                        uploadFormName: "video",
                        uploaderEvent: {
                            onUploadBefore: (file, uploadUrl, headers) => {
                                console.log('视频上传开始:', file.name);
                            },
                            onSuccess: (file, response) => {
                                console.log('视频上传成功:', response);
                            },
                            onFailed: (file, response) => {
                                console.error('视频上传失败:', response);
                            },
                            onError: (file, error) => {
                                console.error('视频上传错误:', error);
                            },
                        }
                    },
                    attachment: {
                        uploadUrl: "/admin/cms/page/upload",
                        uploadFormName: "attachment",
                        uploaderEvent: {
                            onUploadBefore: (file, uploadUrl, headers) => {
                                console.log('附件上传开始:', file.name);
                            },
                            onSuccess: (file, response) => {
                                console.log('附件上传成功:', response);
                            },
                            onFailed: (file, response) => {
                                console.error('附件上传失败:', response);
                            },
                            onError: (file, error) => {
                                console.error('附件上传错误:', error);
                            },
                        }
                    },
                    ai: {
                        models: {
                            spark: {
                                appId: "***",
                                apiKey: "***",
                                apiSecret: "***",
                            }
                        }
                    },
                });
            };
        });
</script>
<script>
    layui.use(['form', 'jquery'], function () {
        let form = layui.form
        let $ = layui.jquery
        
        console.log('Layui form 初始化完成');

        // 特色图像功能
        // 上传图片
        $('#upload-featured-image').click(function() {
            // 创建一个隐藏的文件输入框
            let fileInput = $('<input type="file" accept="image/*" style="display: none;">');
            $('body').append(fileInput);
            
            fileInput.click();
            
            fileInput.on('change', function() {
                let file = this.files[0];
                if (file) {
                    // 创建FormData对象
                    let formData = new FormData();
                    formData.append('image', file);
                    formData.append('type', 'images');
                    
                    // 上传文件
                    $.ajax({
                        url: '/admin/cms/page/upload',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.errorCode === 0) {
                                let imageUrl = result.data.src;
                                $('#featured-image-url').val(imageUrl);
                                showImagePreview(imageUrl);
                                layer.msg('图片上传成功', {icon: 1});
                            } else {
                                layer.msg(result.msg || '上传失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('上传失败', {icon: 2});
                        }
                    });
                }
                
                // 移除临时文件输入框
                fileInput.remove();
            });
        });
        
        // 粘贴图片地址
        $('#paste-image-url').click(function() {
            layer.prompt({
                title: '请输入图片地址',
                formType: 0,
                value: '',
                area: ['400px', '150px']
            }, function(value, index) {
                if (value && value.trim()) {
                    $('#featured-image-url').val(value.trim());
                    showImagePreview(value.trim());
                    layer.close(index);
                    layer.msg('图片地址已设置', {icon: 1});
                } else {
                    layer.msg('请输入有效的图片地址', {icon: 2});
                }
            });
        });
        
        // 移除特色图像
        $('#remove-featured-image').click(function() {
            $('#featured-image-url').val('');
            $('#featured-image-preview').hide();
            layer.msg('特色图像已移除', {icon: 1});
        });
        
        // 显示图片预览
        function showImagePreview(imageUrl) {
            if (imageUrl && imageUrl.trim()) {
                $('#preview-img').attr('src', imageUrl);
                $('#featured-image-preview').show();
            } else {
                $('#featured-image-preview').hide();
            }
        }
        
        // 监听图片地址输入框变化
        $('#featured-image-url').on('input', function() {
            let imageUrl = $(this).val().trim();
            showImagePreview(imageUrl);
        });
        
        // 初始化特色图像预览（如果有值）
        let initialImageUrl = $('#featured-image-url').val();
        if (initialImageUrl) {
            showImagePreview(initialImageUrl);
        }

        // 草稿按钮事件处理
        form.on('submit(page-update)', function (data) {
            console.log('草稿按钮事件触发', data);
            
            // 获取AiEditor的内容
            let editorContent = '';
            
            // 首先尝试从DOM获取内容（最可靠的方法）
            const editorElement = document.querySelector('#editor');
            if (editorElement) {
                // 查找编辑器内的内容区域
                const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                                      editorElement.querySelector('.ai-editor-content') ||
                                      editorElement.querySelector('.editor-content') ||
                                      editorElement;
                
                if (contentElement) {
                    editorContent = contentElement.innerHTML;
                    console.log('从DOM获取到编辑器内容:', editorContent);
                }
            }
            
            // 如果DOM内容为空，尝试使用AiEditor API
            if (!editorContent && window.aiEditor) {
                try {
                    if (typeof window.aiEditor.getContent === 'function') {
                        editorContent = window.aiEditor.getContent();
                    } else if (typeof window.aiEditor.getHtml === 'function') {
                        editorContent = window.aiEditor.getHtml();
                    } else if (typeof window.aiEditor.getMarkdown === 'function') {
                        editorContent = window.aiEditor.getMarkdown();
                    } else if (typeof window.aiEditor.getText === 'function') {
                        editorContent = window.aiEditor.getText();
                    }
                    console.log('从AiEditor API获取到内容:', editorContent);
                } catch (error) {
                    console.error('AiEditor API调用失败:', error);
                }
            }
            
            if (!editorContent) {
                console.warn('无法获取编辑器内容');
            }
            
            // 构建提交数据
            let submitData = {
                id: data.field.postId,
                title: data.field.title,
                slug: data.field.slug,
                excerpt: data.field.excerpt,
                featured_image: data.field.featured_image || '',
                content: editorContent,
                meta_title: data.field.meta_title || '',
                meta_keywords: data.field.meta_keywords || '',
                meta_description: data.field.meta_description || '',
                status: 'draft'  // 保存为草稿
            }
            
            console.log('准备提交的数据:', submitData);
            console.log('提交URL:', '/admin/cms/page/update/' + data.field.postId);
            
            $.ajax({
                url: '/admin/cms/page/update/' + data.field.postId,
                data: JSON.stringify(submitData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    console.log('请求成功:', result);
                    if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                            parent.layui.table.reload('page-table')
                        })
                    } else {
                        layer.msg(result.msg, { icon: 2, time: 1000 })
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败:', xhr, status, error);
                    layer.msg('保存失败: ' + error, { icon: 2, time: 2000 })
                }
            })
            return false
        })
        
        // 发布按钮事件处理
        $('#publish-btn').click(function() {
            console.log('发布按钮事件触发');
            
            // 获取表单数据 - 使用与草稿按钮相同的方式
            let formData = {};
            $('form.layui-form input, form.layui-form textarea, form.layui-form select').each(function() {
                let name = $(this).attr('name');
                let value = $(this).val();
                if (name) {
                    formData[name] = value;
                }
            });
            
            console.log('获取到的表单数据:', formData);
            
            // 获取AiEditor的内容
            let editorContent = '';
            
            // 首先尝试从DOM获取内容（最可靠的方法）
            const editorElement = document.querySelector('#editor');
            if (editorElement) {
                // 查找编辑器内的内容区域
                const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                                      editorElement.querySelector('.ai-editor-content') ||
                                      editorElement.querySelector('.editor-content') ||
                                      editorElement;
                
                if (contentElement) {
                    editorContent = contentElement.innerHTML;
                    console.log('从DOM获取到编辑器内容:', editorContent);
                }
            }
            
            // 如果DOM内容为空，尝试使用AiEditor API
            if (!editorContent && window.aiEditor) {
                try {
                    if (typeof window.aiEditor.getContent === 'function') {
                        editorContent = window.aiEditor.getContent();
                    } else if (typeof window.aiEditor.getHtml === 'function') {
                        editorContent = window.aiEditor.getHtml();
                    } else if (typeof window.aiEditor.getMarkdown === 'function') {
                        editorContent = window.aiEditor.getMarkdown();
                    } else if (typeof window.aiEditor.getText === 'function') {
                        editorContent = window.aiEditor.getText();
                    }
                    console.log('从AiEditor API获取到内容:', editorContent);
                } catch (error) {
                    console.error('AiEditor API调用失败:', error);
                }
            }
            
            if (!editorContent) {
                console.warn('无法获取编辑器内容');
            }
            
            // 构建提交数据
            let submitData = {
                id: formData.postId,
                title: formData.title,
                slug: formData.slug,
                excerpt: formData.excerpt,
                featured_image: formData.featured_image || '',
                content: editorContent,
                meta_title: formData.meta_title || '',
                meta_keywords: formData.meta_keywords || '',
                meta_description: formData.meta_description || '',
                status: 'published'  // 发布状态
            }
            
            console.log('准备发布的数据:', submitData);
            console.log('发布URL:', '/admin/cms/page/update/' + formData.postId);
            
            $.ajax({
                url: '/admin/cms/page/update/' + formData.postId,
                data: JSON.stringify(submitData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    console.log('请求成功:', result);
                    if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                            parent.layui.table.reload('page-table')
                        })
                    } else {
                        layer.msg(result.msg, { icon: 2, time: 1000 })
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败:', xhr, status, error);
                    layer.msg('发布失败: ' + error, { icon: 2, time: 2000 })
                }
            })
        })
    })
</script>

</body>
</html>